package com.boot2.core.web.websocket;

import com.boot2.core.conf.CorsConf;
import com.boot2.core.utils.ThreadPoolTaskExecutorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.StompWebSocketEndpointRegistration;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * @author zhangweilin
 * @date 2018/7/4 17:22
 * @description: 同步实时推送的websocket 配置
 */
//@Configuration
//@EnableWebSocketMessageBroker
public class AbstractWebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired(required = false)
    CorsConf corsConf;

    @Autowired(required = false)
    AbstractHandshakeInterceptor abstractHandshakeInterceptor;

    @Autowired(required = false)
    ResultChannelInterceptor resultChannelInterceptor;

    @Autowired(required = false)
    ResultMessageConverter resultMessageConverter;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        ///ws就是websocket的端点，客户端需要注册这个端点进行链接，withSockJS允许客户端利用sockjs进行浏览器兼容性处理
//        System.out.println("ArrayUtils.toString(allowedOrigins) = " + ArrayUtils.toString(allowedOrigins));
        StompWebSocketEndpointRegistration stompWebSocketEndpointRegistration = registry.addEndpoint("/ws");
        if (null != abstractHandshakeInterceptor) {
            stompWebSocketEndpointRegistration.addInterceptors(abstractHandshakeInterceptor).setHandshakeHandler(new DefaultHandshakeHandler() {
                @Override
                protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
                    //设置认证用户

                    return (Principal) attributes.get("user");
                }
            });
        }

        if (null != corsConf) {
            String[] allowedOrigins = corsConf.getWebsocketAllowedOrigins();
            if (null != allowedOrigins) {
                stompWebSocketEndpointRegistration.setAllowedOrigins(allowedOrigins);
            } else {
                stompWebSocketEndpointRegistration.setAllowedOrigins("*");
            }
        } else {
            stompWebSocketEndpointRegistration.setAllowedOrigins("*");
        }
//        stompWebSocketEndpointRegistration.setAllowedOrigins("*");
        stompWebSocketEndpointRegistration.withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //设置客户端订阅消息的基础路径
        registry.setApplicationDestinationPrefixes("/ws");
        //设置客户端接收点对点消息地址的前缀，默认为 /user
        registry.setUserDestinationPrefix("/user");
        ///topic设置服务器广播消息的基础路径   ///queue为点对点发送给指定用户
        registry.enableSimpleBroker("/topic", "/queue");
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.taskExecutor(ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor(0.3));
        resultChannelInterceptor = resultChannelInterceptor == null ? new ResultChannelInterceptor() : resultChannelInterceptor;
        registration.interceptors(resultChannelInterceptor);
    }


    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        resultMessageConverter = resultMessageConverter == null ? new ResultMessageConverter() : resultMessageConverter;
        messageConverters.add(resultMessageConverter);
        return true;
    }


//    @Override
//    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
//
//    }
//
//    @Override
//    public void configureClientInboundChannel(ChannelRegistration registration) {
//
//    }
//
//    @Override
//    public void configureClientOutboundChannel(ChannelRegistration registration) {
//
//    }
//
//    @Override
//    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//
//    }
//
//    @Override
//    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
//
//    }
//
//    @Override
//    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
//        return false;
//    }


//    @Override
//    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
//
//        return true;
//    }
//
//    @Override
//    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
//        // TODO Auto-generated method stub
//        registry.addDecoratorFactory(new MyWebSocketHandlerDecoratorFactory());
//    }
//
//    @Override
//    public void configureClientInboundChannel(ChannelRegistration registration) {
//        registration.setInterceptors(new MyChannelInterceptor());
//    }
//
//    @Override
//    public void configureClientOutboundChannel(ChannelRegistration registration) {
//        // TODO Auto-generated method stub
//
//    }
//
//    @Override
//    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//        // TODO Auto-generated method stub
//
//    }
}
